package org.jeecg.activiti.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.activiti.entity.ActReModelExtend;
import org.jeecg.activiti.entity.ActReModelFormData;
import org.jeecg.activiti.service.IActReModelExtendService;
import org.jeecg.activiti.service.IActReModelFormDataService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
 * TODO
 *
 * @author dousw
 * @version 1.0
 * @date 2020/9/15 11:04
 */
@RestController
@RequestMapping("/activiti/formData")
@Api(tags = "流程表单数据管理")
public class ActivitiFormDataController {

    @Autowired
    private IActReModelFormDataService iActReModelFormDataService;

    @Autowired
    private IActReModelExtendService iActReModelExtendService;

    @GetMapping("/list")
    @ApiOperation(value = "查询流程表单数据", notes = "查询流程表单数据")
    public Result<IPage<Map<String,Object>>> list(ActReModelFormData actReModelFormData,
                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<Map<String,Object>>> result = new Result<>();
        Page<ActReModelFormData> page = new Page<>(pageNo,pageSize);
        page = iActReModelFormDataService.pageList(page, actReModelFormData);
        List<Map<String,Object>> resultList = new ArrayList<>();

        for (ActReModelFormData formData : page.getRecords()) {

            ActReModelExtend actME = iActReModelExtendService.getOne(new QueryWrapper<ActReModelExtend>().eq("model_id", formData.getModelId()));

            Map<String,Object> reMap = new HashMap<>();
            reMap.put("formId", formData.getFormId());
            reMap.put("formData", formData.getFormData());
            reMap.put("modelId", formData.getModelId());
            reMap.put("formDataId", formData.getId());
            reMap.put("status", formData.getStatus());
            reMap.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(formData.getCreateTime()));

            reMap.put("modelName", formData.getModelName());
            reMap.put("modelKey", formData.getModelKey());
            
            reMap.put("tableId", formData.getTableId());
            reMap.put("tableName", formData.getTableName());
            reMap.put("dataId", formData.getDataId());

            reMap.put("businessPlate", actME.getBusinessPlate());
            reMap.put("processInstanceId", formData.getProcessInstanceId());
			reMap.put("processDefinitionId", formData.getProcessDefinitionId());
			reMap.put("reportCode", actME.getReportCode());
            resultList.add(reMap);
        }

        IPage<Map<String,Object>> resultPage = new Page<>();
        resultPage.setPages(page.getPages());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        resultPage.setTotal(page.getTotal());

        resultPage.setRecords(resultList);

        result.setSuccess(true);
        result.setResult(resultPage);
        return result;
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "流程表单数据保存/修改", notes = "流程表单数据保存/修改")
    public Result<Object> saveOrUpdate(@RequestBody ActReModelFormData actReModelFormData) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isEmpty(actReModelFormData.getId())) {
            actReModelFormData.setCreateBy(sysUser.getUsername());
            actReModelFormData.setCreateTime(new Date());

            iActReModelFormDataService.save(actReModelFormData);
        } else {
            actReModelFormData.setUpdateBy(sysUser.getUsername());
            actReModelFormData.setUpdateTime(new Date());
            iActReModelFormDataService.updateById(actReModelFormData);
        }

        return Result.OK(actReModelFormData);
    }

    @GetMapping("/getFormDataByProcessInstanceId")
    @ApiOperation(value = "根据流程实例ID查询流程表单数据", notes = "根据流程实例ID查询流程表单数据")
    public Result<Object> getFormDataByProcessInstanceId(@ApiParam(name="processInstanceId", value="流程实例ID", required = true) @RequestParam(name="processInstanceId",required=true) String processInstanceId,
                                                         @ApiParam(name="taskId", value="任务ID", required = false) @RequestParam(name="taskId",required=false) String taskId) {
        ActReModelFormData actReModelFormData = this.iActReModelFormDataService.getOne(new QueryWrapper<ActReModelFormData>().eq("process_instance_id", processInstanceId));

        if(actReModelFormData == null) {
    		return Result.error("未找到数据 [ processInstanceId:" + processInstanceId + " ]");
    	}

        if(taskId != null && !"".equals(taskId)){
        	List<Map<String, Object>> appendFormList = iActReModelFormDataService.handleNodeAppendForm(taskId, processInstanceId);
            actReModelFormData.setAppendFormList(appendFormList);
        }

        return Result.OK(actReModelFormData);
    }

    /**
     * 删除模型
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @ApiOperation(value = "流程表单数据删除", notes = "流程表单数据删除")
    public Result<?>  delete(@ApiParam(name="id", value = "ID", required = true) @RequestParam(name="id",required=true) String id){
        // 删除流程定义
        iActReModelFormDataService.removeById(id);
        return Result.OK();
    }

    /**
     * 批量删除模型
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    @ApiOperation(value = "流程表单数据批量删除", notes = "流程表单数据批量删除")
    public Result<Object> deleteBatch(@ApiParam(name="ids", value = "IDS", required = true) @RequestParam(name="ids",required=true) String ids) {
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            iActReModelFormDataService.removeById(id);
        }
        return Result.OK();
    }
}
